<template>
  <div>
    <van-nav-bar
      title="选择收货地址"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    <Search @search="search"></Search>

    <van-cell
      v-for="(item, i) in searchList"
      :key="i"
      :title="item.name"
      :label="item.address"
      @click="clickObj(item)"
    />
    <div class="history">
      <p>搜索历史</p>

      <div class="tag-warp">
        <span
          class="tag"
          v-for="(item, i) in history"
          :key="i"
          @click="clickHistory(item)"
        >
          {{ item.name }}</span
        >
      </div>
    </div>
  </div>
</template>

<script>
import Search from './search.vue'
import { searchAddress } from '@/api/address'
export default {
  data() {
    return {
      city: {},
      searchList: [],
      timer: null,
      history: [],
    }
  },
  components: {
    Search,
  },
  created() {
    this.city = JSON.parse(localStorage.getItem('currentCity'))
    this.history = JSON.parse(localStorage.getItem('history')) || []
  },
  methods: {
    onClickLeft() {
      this.$router.back()
    },
    search(value) {
      if (this.timer) clearTimeout(this.timer)
      this.timer = setTimeout(async () => {
        const { data } = await searchAddress({
          city_id: this.city.id,
          keyword: value,
        })
        this.searchList = data
      }, 900)
    },
    clickObj(item) {
      this.$router.push('/home')
      this.history.unshift(item)
      this.$store.commit('setcurrentAddress', item)
      localStorage.setItem('history', JSON.stringify(this.history))
    },
    clickHistory(item) {
      this.$store.commit('setcurrentAddress', item)
      this.$router.push('/home')
    },
  },
}
</script>

<style lang='less' scoped>
.van-nav-bar {
  background-color: #3190e8;
  /deep/ .van-nav-bar__title {
    color: #fff;
  }
  /deep/ .van-nav-bar__text {
    color: #fff;
  }
  /deep/ .van-icon {
    color: #fff;
  }
}
.history {
  padding: 0 16px;
  p {
    margin: 0;
    font-size: 14px;
  }
}
.tag-warp {
  .tag {
    display: inline-block;
    padding: 0 20px;
    margin: 10px 10px 0 0;
    height: 35px;
    line-height: 35px;
    background-color: #eee;
    font-size: 14px;
  }
}
</style>